package cnpm02.j2ee.group3.logic.validator;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.validator.Validator;
import org.jboss.seam.Component;
import org.jboss.seam.core.Expressions;

public class UniqueTwoFieldsValidator implements Validator<UniqueTwoFields> {
	private String sql;
	private String param1;
	private String param2;
	private String id2;
	public void initialize(UniqueTwoFields value) {
		sql = value.sql();
		id2 = value.id2();
		param1 = value.parameterName1();
		param2 = value.parameterName2();
	}

	public boolean isValid(Object value) {
		EntityManager entityManager = (EntityManager) Component
				.getInstance("entityManager");
		
		Query query = entityManager.createQuery(sql);
		query.setParameter(param1, value);
		Object value2 = Expressions.instance().createValueExpression(id2)
				.getValue().toString();
		query.setParameter(param2, value2);
		if (query.getResultList().size() > 0) {
			return false;
		} else {
			return true;
		}
	}
}
